package top.kaoshanji.p3ch17a;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;

/**
 * 代码清单-p3ch17a-290页a：动态注册Servlet的监听器
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 16:39
 */
@WebListener
public class DynRegListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();

        // Servlet 对象
        Servlet firstServlet = null;
        try {
            firstServlet = servletContext.createServlet(FirstServlet.class);
        } catch (ServletException e) {
            e.printStackTrace();
        }

        if (firstServlet != null && firstServlet instanceof FirstServlet) {
            ((FirstServlet)firstServlet).setName("Dynamically registered servlet");
        }

        // 注册 Servlet，等同于 @WebServlet
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("firstServlet", firstServlet);
        dynamic.addMapping("/dynamic");

    }


}
